package com.ydy.file.controller;

import cn.afterturn.easypoi.cache.manager.POICacheManager;
import cn.afterturn.easypoi.excel.ExcelXorHtmlUtil;
import cn.afterturn.easypoi.excel.entity.ExcelToHtmlParams;
import com.ydy.common.BaseController;
import com.ydy.common.constant.Constant;
import com.ydy.common.model.FileInfo;
import com.ydy.common.util.ParamsUtil;
import com.ydy.common.util.RedisUtil;
import com.ydy.file.service.FileService;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

@RestController
public class ExcelController extends BaseController {

    private static Logger LOGGER = LoggerFactory.getLogger(ExcelController.class);

    @Autowired
    private FileService fileService;

    @Autowired
    private RedisTemplate<Serializable, Object> redisTemplate;

    @PostMapping(value = "/excelUpload")
    public Object excelUpload(@RequestParam(value = "file", required = false) MultipartFile file){

        FileInfo fileInfo = fileService.getFileInfo(file,Constant.FILE_EXCEL);

        return retResultVo(fileInfo);
    }



    /**
     * excel在线预览
     * @Title: showH5FromExcelFile
     * @author: dy.yin 2021/4/13 15:45
     * @param: [request]
     * @return: java.lang.Object
     * @throws
     */
    @GetMapping("/showH5FromExcelFile")
    public Object showH5FromExcelFile(HttpServletRequest request) {

        FileInfo fileInfo = ParamsUtil.getBeanParam(new FileInfo(),request);
        RedisUtil redisUtil = new RedisUtil(redisTemplate);
        String serveUrl = String.valueOf(redisUtil.get(Constant.SERVE_URL));

        String fileAddress = fileInfo.getFileUrl().replace(serveUrl,"");
        ExcelToHtmlParams params = null;
        try {
            params = new ExcelToHtmlParams(WorkbookFactory.create(
                    POICacheManager.getFile(fileAddress)));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info(e.getLocalizedMessage());
        }
        String views = ExcelXorHtmlUtil.excelToHtml(params);
        return retResultVo(views);
    }
}
